
const glob = require("glob");
const { resolve, join, basename } = require("path");

const argv = require('yargs-parser')(process.argv.slice(2));
const merge = require('webpack-merge');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin');
const HtmlBeforeWebpackPlugin = require('./config/html-before-webpack-plugin');


const _mode = argv.mode || "development";
const _modeflag = (_mode == "production" ? true : false);
const _mergeConfig = require(`./config/webpack.${argv.mode}.js`);

const files = glob.sync("./src/webapp/views/**/*.entry.js");

let _entry = {};
let _plugins = [];
for (let item of files) {
  // item.replace(/.+\/([a-zA-Z]+-[a-zA-Z]+)(\.entry\.js$)/g, (mactch, $1) => {
  //     _entry[$1] = item
  // });
  if (/.+\/([a-zA-Z]+-[a-zA-Z]+)(\.entry\.js$)/g.test(item) == true) {
    const entrykey = RegExp.$1
    _entry[entrykey] = item;
    const [dist, template] = entrykey.split("-");
    _plugins.push(new HtmlWebpackPlugin({
      filename: `../views/${dist}/pages/${template}.html`,
      template: `src/webapp/views/${dist}/pages/${template}.html`,
      chunks: ["runtime", "common", entrykey],
      minify: {
        // removeComments: true,
        collapseWhitespace: _modeflag,
        removeAttributeQuotes: _modeflag
        // https://github.com/kangax/html-minifier#options-quick-reference
      },
      inject: false
    }));
  }
}
//console.log(_entry);
let webpackConfig = {
  entry: _entry,
  output: {
    path: join(__dirname, './dist/assets'),
    publicPath: "/",
    filename: "scripts/[name].bundle.js"
  },
  module: {
    rules: [
      {
        test: /\.(png|jpg|gif|eot|woff|woff2|ttf|svg|otf)$/,
        use: [{
          loader: 'file-loader',
          options: {
            name: _modeflag ? "images/[name].[hash:5].[ext]" : "images/[name].[ext]"
          }
        }]
      },
      {
        test: /\.css$/,
        exclude: /node_modules/,
        use: ExtractTextPlugin.extract({
          fallback: "style-loader",
          use: [
            { 
              loader: 'css-loader', 
              options: { 
                importLoaders: 1, 
                minimize: _modeflag ? true : false 
              } 
            },
            'postcss-loader'
          ]
        })
      }
    ]
  },
  optimization: {
      //原CommonsChunkPlugin配置
      splitChunks: {
          cacheGroups: {
              common: {
                  //test: resolve(__dirname, "node_modules"), // 路径在 node_modules 目录下的都作为公共部分
                  chunks: 'all',
                  name: 'common',
                  minChunks: 2
              },
              // common-async: {
              //     chunks: "async",
              //     name: "common",
              //     minChunks: 2
              // }
          }
      },
      runtimeChunk: { name: 'runtime' }
  },
  plugins: [
    ..._plugins,
    new HtmlBeforeWebpackPlugin()
  ],
  resolve: {
      modules: [
          // resolve方法，需要从path模块引入
          resolve(__dirname, 'node_modules'), // 使用绝对路径指定 node_modules，不做过多查询
      ],
      // 删除不必要的后缀自动补全，少了文件后缀的自动匹配，即减少了文件路径查询的工作
      extensions: [".js", ".css"]
  }
}

module.exports = merge(webpackConfig, _mergeConfig);
